<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-17px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目主管" prop="charge">
        <el-input
          v-model="queryParams.charge"
          class="!w-240px"
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目阶段" prop="value">
        <el-select
          v-model="queryParams.value"
          placeholder="请选择"
          @change="handleQuery"
          class="!w-240px"
          placement="bottom"
        >
          <el-option v-for="item in stageList" :key="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目角色" prop="role">
        <el-select
          v-model="queryParams.role"
          placeholder="请选择"
          @change="handleQuery"
          class="!w-240px"
          placement="bottom"
        >
          <el-option v-for="item in roleList" :key="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table
      :data="list"
      v-loading="loading"
      empty-text="暂无项目"
      element-loading-text="Loading..."
      stripe
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      show-overflow-tooltip
    >
      <el-table-column align="center" label="项目化核算编码" prop="project_code" width="180" />
      <el-table-column align="center" label="项目名称" prop="project_name" min-width="200">
        <template #default="scope">
          <div class="namecont" v-html="highlightProjectName(scope.row.project_name)"></div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="建设单位"
        prop="construction_department"
        min-width="120"
      />
      <el-table-column
        align="center"
        label="省端项目主管"
        prop="construction_department"
        min-width="120"
      >
        <template #default="scope">
          <div
            class="namecont"
            v-html="highlightprojectSupervisor(scope.row.project_supervisor)"
          ></div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目阶段" prop="projectStage" min-width="120">
        <template #default="scope">
          <div class="flex justify-center">
            <el-tag effect="light">{{ scope.row.projectStage }} </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="160">
        <template #default="scope">
          <el-button
            link
            type="primary"
            :icon="DocumentRemove"
            @click="handleAudit(scope.row)"
            class="text-#409eff"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="mt-35px text-14px"
      v-model:current-page="queryParams.pageNo"
      :hide-on-single-page="value"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      background
      layout="total,sizes,prev, pager, next,jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </ContentWrap>
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted } from 'vue'
import { DocumentRemove } from '@element-plus/icons-vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { staticData } from '@/views/project/mixins/staticDataMixin'

const { push } = useRouter() // 路由
// 获取当前登录用户
const { wsCache } = useCache()
const currentUser = wsCache.get(CACHE_KEY.USER).user.id
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const Alllist = ref([]) // 总数据
const value = ref(true)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  charge: '',
  value: '',
  role: ''
})

const queryFormRef = ref()
const { stageList } = staticData()

const roleList = ['项目交底人', '建设单位部门经理', '交付经理', '服务经理', '省端项目主管']
const roleMapping = {
  项目交底人: 'project_receiver_id',
  建设单位部门经理: 'construction_department_manager_id',
  交付经理: 'construction_project_manager_id',
  服务经理: 'maintenance_manager_id',
  省端项目主管: 'project_supervisor_id'
}

// 条数变化
const handleSizeChange = (e) => {
  queryParams.pageSize = e
  queryParams.pageNo = 1
  getMyProjectsList()
}

// 页码变化
const handleCurrentChange = (e) => {
  queryParams.pageNo = e
  getMyProjectsList()
}

// 数据分页
const listcheck = () => {
  list.value = Alllist.value.slice(
    (queryParams.pageNo - 1) * queryParams.pageSize,
    queryParams.pageNo * queryParams.pageSize
  )
  if (list.value.length === 0) {
    value.value = true
  } else {
    value.value = false
  }
}

// 查询任务列表
const getMyProjectsList = async () => {
  // 获取获取我的项目列表
  return new Promise<void>((resolve, reject) => {
    KmsApi.getMylProjectsList()
      .then((res) => {
        let data = reactive(res) || []
        loading.value = false
        if (!data || data.length === 0) {
          listcheck()
          resolve()
          return // 退出函数，不执行后续请求
        }
        const projectList: Array<string> = []
        data.forEach((item: { project_code: string }) => {
          projectList.push(item.project_code)
        })
        //获取批量获取项目流程阶段
        const projectsData = {
          project_code_list: projectList
        }
        BpmApi.getProjectStage(projectsData)
          .then((res) => {
            let newdata = reactive(res)
            data.forEach(
              (item: {
                project_code: string | number
                processInstanceId: any
                projectStage: any
                tasksName: any
              }) => {
                if (newdata[item.project_code]) {
                  item.processInstanceId = newdata[item.project_code][0].id
                  item.projectStage = item.projectStage = item.finished
                    ? '已结束'
                    : newdata[item.project_code][0].name
                  item.tasksName = newdata[item.project_code][0].process_definition_name
                }
              }
            )
            Alllist.value = data
            total.value = data.length
            listcheck()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
      .catch((error) => {
        loading.value = false
        reject(error)
      })
  })
}

// 详情按钮跳转
const handleAudit = (row: any) => {
  push({
    name: 'ProjectDetails',
    query: {
      project_code: row.project_code
    }
  })
}

// 搜索按钮操作
const handleQuery = async () => {
  queryParams.pageNo = 1
  await getMyProjectsList()

  Alllist.value = Alllist.value.filter((item) => {
    return Object.entries(queryParams).every(([key, value]) => {
      if (value === '') return true // 如果查询参数为空，不进行筛选

      if (key === 'role') {
        const itemKey = roleMapping[value]
        return itemKey && itemKey in item
          ? item[itemKey].toString() === currentUser.toString()
          : false
      }

      const itemKey = {
        name: 'project_name',
        charge: 'project_supervisor',
        value: 'projectStage'
      }[key]

      // 确保item有这个属性，并且包含查询值
      return itemKey && itemKey in item ? item[itemKey].includes(value) : true
    })
  })

  total.value = Alllist.value.length
  listcheck()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 初始化
onMounted(() => {
  getMyProjectsList()
})

const escapeRegExp = (string: string): string => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

const highlightProjectName = (name: string): string => {
  if (!queryParams.name) {
    return name
  }
  const regex = new RegExp(escapeRegExp(queryParams.name), 'gi')
  const newText = name.replace(regex, (match) => `<span class="highlight">${match}</span>`)
  return newText
}

const highlightprojectSupervisor = (name: string): string => {
  if (!queryParams.charge) {
    return name
  }
  const regex = new RegExp(escapeRegExp(queryParams.charge), 'gi')
  const newText = name.replace(regex, (match) => `<span class="highlight">${match}</span>`)
  return newText
}
</script>
<style scoped>
.el-pagination {
  justify-content: flex-end;
}
.namecont {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}

:deep(.highlight) {
  background-color: yellow;
}
</style>